<template>
  <div class="dashboard">
    <!-- 数据统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总用户数</span>
            </div>
          </template>
          <div class="card-body">
            <span class="number">{{ statistics.totalUsers }}</span>
            <el-icon><User /></el-icon>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日预约</span>
            </div>
          </template>
          <div class="card-body">
            <span class="number">{{ statistics.todayReservations }}</span>
            <el-icon><Calendar /></el-icon>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日订单</span>
            </div>
          </template>
          <div class="card-body">
            <span class="number">{{ statistics.todayOrders }}</span>
            <el-icon><ShoppingCart /></el-icon>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日收入</span>
            </div>
          </template>
          <div class="card-body">
            <span class="number">¥{{ statistics?.todayIncome?.toFixed(2) || '0.00' }}</span>
            <el-icon><Money /></el-icon>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>近7天预约统计</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="reservationChart" style="height: 300px"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>近7天收入统计</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="incomeChart" style="height: 300px"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 列表区域 -->
    <el-row :gutter="20" class="list-row">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最新预约</span>
              <el-button text @click="$router.push('/admin/study-room')">查看更多</el-button>
            </div>
          </template>
          <el-table :data="latestReservations" style="width: 100%">
            <el-table-column prop="username" label="用户" width="100" />
            <el-table-column prop="roomName" label="自习室" width="120" />
            <el-table-column prop="seatNumber" label="座位号" width="100" />
            <el-table-column prop="startTime" label="开始时间" width="160">
              <template #default="scope">
                {{ scope.row.startTime }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最新订单</span>
              <el-button text @click="$router.push('/admin/order')">查看更多</el-button>
            </div>
          </template>
          <el-table :data="latestOrders" style="width: 100%">
            <el-table-column prop="username" label="用户" width="120" />
            <el-table-column prop="deliveryLocation" label="送达地点" show-overflow-tooltip />
            <el-table-column prop="totalAmount" label="金额" width="100">
              <template #default="scope">
                ¥{{ scope.row.totalAmount?.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getOrderStatusType(scope.row.status)">
                  {{ getOrderStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.createdAt) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { User, Calendar, ShoppingCart, Money } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import request from '@/utils/request'
import { formatDateTime } from '@/utils/dateUtil'

export default {
  name: 'Dashboard',
  components: {
    User,
    Calendar,
    ShoppingCart,
    Money
  },
  setup() {
    const statistics = ref({
      totalUsers: 0,
      todayReservations: 0,
      todayOrders: 0,
      todayIncome: 0.00
    })
    
    const latestReservations = ref([])
    const latestOrders = ref([])
    const reservationChart = ref(null)
    const incomeChart = ref(null)
    
    const loadStatistics = async () => {
      try {
        const res = await request.get('/admin/statistics')
        if (res.code === 200 && res.data) {
          statistics.value = {
            ...res.data,
            todayIncome: Number(res.data.todayIncome) || 0.00
          }
        }
      } catch (error) {
        console.error('Failed to load statistics:', error)
      }
    }
    
    const loadLatestData = async () => {
      try {
        const [reservationsRes, ordersRes] = await Promise.all([
          request.get('/admin/statistics/latest-reservations'),
          request.get('/admin/statistics/latest-orders')
        ])
        if (reservationsRes.code === 200) {
          latestReservations.value = reservationsRes.data
        }
        if (ordersRes.code === 200) {
          latestOrders.value = ordersRes.data
        }
      } catch (error) {
        console.error('Failed to load latest data:', error)
      }
    }
    
    const initCharts = async () => {
      try {
        const [reservationRes, incomeRes] = await Promise.all([
          request.get('/admin/statistics/reservation-chart'),
          request.get('/admin/statistics/income-chart')
        ])
        
        if (reservationRes.code === 200 && incomeRes.code === 200) {
          // 初始化预约统计图表
          const reservationChartInstance = echarts.init(reservationChart.value)
          reservationChartInstance.setOption({
            title: { text: '近7天预约统计' },
            tooltip: { 
              trigger: 'axis',
              formatter: (params) => {
                return `${params[0].name}<br/>预约数：${params[0].value}`
              }
            },
            xAxis: {
              type: 'category',
              data: reservationRes.data.xAxis,
              axisLabel: {
                rotate: 30,
                interval: 0  // 显示所有标签
              }
            },
            yAxis: { 
              type: 'value',
              minInterval: 1  // 保证y轴步长为整数
            },
            grid: {
              bottom: 60  // 增加底部空间，防止x轴标签显示不全
            },
            series: [{
              data: reservationRes.data.series,
              type: 'line',
              smooth: true,
              symbolSize: 8,  // 增加数据点大小
              label: {
                show: true,
                position: 'top'
              }
            }]
          })
          
          // 初始化收入统计图表
          const incomeChartInstance = echarts.init(incomeChart.value)
          incomeChartInstance.setOption({
            title: { text: '近7天收入统计' },
            tooltip: {
              trigger: 'axis',
              formatter: (params) => {
                return `${params[0].name}<br/>收入：¥${params[0].value.toFixed(2)}`
              }
            },
            xAxis: {
              type: 'category',
              data: incomeRes.data.xAxis,
              axisLabel: {
                rotate: 30,
                interval: 0  // 显示所有标签
              }
            },
            yAxis: { 
              type: 'value',
              axisLabel: {
                formatter: (value) => `¥${value}`
              }
            },
            grid: {
              bottom: 60  // 增加底部空间
            },
            series: [{
              data: incomeRes.data.series,
              type: 'line',
              smooth: true,
              symbolSize: 8,
              label: {
                show: true,
                position: 'top',
                formatter: (params) => `¥${params.value}`
              }
            }]
          })

          // 监听窗口大小变化，重新渲染图表
          window.addEventListener('resize', () => {
            reservationChartInstance.resize()
            incomeChartInstance.resize()
          })
        }
      } catch (error) {
        console.error('Failed to init charts:', error)
      }
    }
    
    const getOrderStatusType = (status) => {
      const types = {
        0: 'info',    // 待支付
        1: 'warning', // 已支付
        2: '',        // 配送中
        3: 'success', // 已完成
        4: 'danger'   // 已取消
      }
      return types[status]
    }
    
    const getOrderStatusText = (status) => {
      const texts = {
        0: '待支付',
        1: '已支付',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      }
      return texts[status]
    }
    
    const loadLatestOrders = async () => {
      try {
        const res = await request.get('/admin/orders/latest')
        if (res.code === 200) {
          // 添加调试日志
          console.log('Latest orders raw data:', res.data)
          latestOrders.value = res.data
        }
      } catch (error) {
        console.error('Failed to load latest orders:', error)
      }
    }
    
    onMounted(() => {
      loadStatistics()
      loadLatestData()
      loadLatestOrders()
      initCharts()
    })
    
    return {
      statistics,
      latestReservations,
      latestOrders,
      reservationChart,
      incomeChart,
      getOrderStatusType,
      getOrderStatusText,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.dashboard {
  .el-row {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .card-body {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .number {
      font-size: 24px;
      font-weight: bold;
    }
    
    .el-icon {
      font-size: 48px;
      color: #409EFF;
    }
  }
  
  .chart-container {
    height: 300px;
  }
}
</style> 